document.addEventListener('DOMContentLoaded', async () => {
  const form = document.getElementById('proxyForm');
  const statusMessage = document.getElementById('statusMessage');
  const resetButton = document.getElementById('resetButton');

  // 从存储中加载现有配置
  const { proxyConfig } = await chrome.storage.local.get('proxyConfig');
  if (proxyConfig) {
    document.getElementById('host').value = proxyConfig.host;
    document.getElementById('port').value = proxyConfig.port;
    document.getElementById('username').value = proxyConfig.username || '';
    document.getElementById('password').value = proxyConfig.password || '';
  }

  // 显示状态消息
  function showStatus(message, isError = false) {
    statusMessage.textContent = message;
    statusMessage.style.display = 'block';
    statusMessage.className = `status-message ${isError ? 'error' : 'success'}`;
    setTimeout(() => {
      statusMessage.style.display = 'none';
    }, 3000);
  }

  // 处理表单提交
  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const config = {
      host: document.getElementById('host').value.trim(),
      port: parseInt(document.getElementById('port').value),
      username: document.getElementById('username').value.trim(),
      password: document.getElementById('password').value.trim()
    };

    // 验证输入
    if (!config.host) {
      showStatus('请输入服务器地址', true);
      return;
    }
    if (!config.port || config.port < 1 || config.port > 65535) {
      showStatus('请输入有效的端口号（1-65535）', true);
      return;
    }

    try {
      // 保存配置
      await chrome.storage.local.set({ proxyConfig: config });
      
      // 通知background script更新代理设置
      chrome.runtime.sendMessage({
        type: 'updateProxyConfig',
        config: config
      });

      showStatus('设置已保存');
    } catch (error) {
      showStatus('保存设置时出错：' + error.message, true);
    }
  });

  // 重置按钮处理
  resetButton.addEventListener('click', () => {
    form.reset();
    showStatus('设置已重置');
  });
});